<template>
  <view class="page">
    <view class="block-title">隔离点</view>
    <view class="info">
      <view class="info-item">
        <view>隔离点名称</view>
        <view>{{ formData.supervisionName || "" }}</view>
      </view>
      <view class="info-item">
        <view>负责人</view>
        <input
          v-model="formData.supervisionUserName"
          type="text"
          placeholder="请输入"
          maxlength="30"
          class="input-right"
        />
      </view>
      <view class="info-item">
        <view>联系电话</view>
        <input
          v-model="formData.supervisionPhone"
          type="number"
          placeholder="请输入"
          maxlength="12"
          class="input-right"
        />
      </view>
    </view>
    <view class="block-title">督导员</view>
    <view class="info">
      <view class="info-item">
        <view>负责人</view>
        <view>{{ formData.stagnationPointName || "" }}</view>
      </view>
      <view class="info-item">
        <view>联系电话</view>
        <view>{{ formData.stagnationPointNamePhone || "" }}</view>
      </view>
      <view class="info-item">
        <view>督导检查时间</view>
        <view>{{ formData.supervisionTime || "" }}</view>
      </view>
    </view>
    <view class="block-title">
      <text>督导项目</text>
      <view class="check-all" @click="checkAll">全部已落实</view>
    </view>
    <view class="subject-content">
      <uni-forms
        :value="formData"
        ref="form"
        validate-trigger="bind"
        err-show-type="undertext"
      >
        <view v-for="(item, index) in subjectList" :key="index" class="subject-item">
          <view class="sub-title">{{ item.name }}</view>
          <view v-for="(t,i) in item.children" :key="i" class="flex-box">
            <view v-if="!t.workText">
              <textarea
                v-model="t.text"
                type="textarea"
                placeholder="请输入内容"
                maxlength="300"
                auto-height
                placeholder-style="color: #ccc;"
              />
            </view>
            <block v-else>
              <view class="form-title">{{ t.workText }}</view>
              <view>
                <uni-data-checkbox
                  :value="t.value"
                  :localdata="checkRange"
                  class="my-raido"
                  @change="checkItem($event, t)"
                ></uni-data-checkbox>
              </view>
              <view v-if="t.value === 1" class="form-ext">
                <!-- textarea -->
                <view class="form-title">情况说明</view>
                <view>
                  <textarea
                    v-model="t.text"
                    type="textarea"
                    placeholder="请输入内容"
                    maxlength="300"
                    auto-height
                    placeholder-style="color: #ccc;"
                  />
                </view>
              </view>
            </block>
          </view>
        </view>
        <!-- 图片上传 -->
        <view class="sub-title">如有违规行为，请拍摄违规现场照片上传</view>
        <view  class="unload-item">
          <view class="upload-btn mg-right"  v-for="(item,index) in imgList" :key="index">
            <view class="close" @click="deleteImg(index)">
              <image class="close-img"  src="https://szgd-dev.tgovcloud.com/public/images/referral/icon-close.png" mode="widthFix"></image>
            </view>
            <image class="full-img"  :src="item.filePath" mode="aspectFit" @click="preview(imgList)"></image>
          </view>
          <view class="upload-btn" @click="chooseImg">
            <image class="middle-img"  src="https://szgd-dev.tgovcloud.com/public/images/referral/icon-addfile.png" mode="widthFix"></image>
          </view>
        </view>
      </uni-forms>
    </view>

    <view class="handle-btn">
      <button type="primary" @click="submit">提交</button>
    </view>
  </view>
</template>

<script>
import { subjectList } from './formConfig';
import dayjs from 'dayjs';
import { getData, getSupervisionQuestion, addSupervision } from '@/api';

export default {
  data() {
    return {
      dayjs,
      formData: {},
      subjectList: [],
      question: [],
      checkRange: [
        { value: 0, text: '已落实' },
        { value: 1, text: '未落实' },
      ],
      imgList: [],
    }
  },
  onLoad() {
    const personInfo = uni.getStorageSync('personalInfo');
    this.formData = {
      supervisionName: personInfo.isolationName,
      supervisionUserName: '',
      supervisionPhone: '',
      isolationHotelId: personInfo.isolationId,
      stagnationPointName: personInfo.name,
      stagnationPointNamePhone: personInfo.phone,
      supervisionTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      supervisionRelationProjects: [], // 题目
      fileId: '', // 附件id分隔列表
    }
    getData('hotelAdmin', 'get', { hotelId: personInfo.isolationId }).then(res => {
      let data = res || [];
      this.formData.supervisionUserName = data[0] ? data[0].name : '';
      this.formData.supervisionPhone = data[0] ? data[0].phone : '';
    })
    this.getQuestionList();
  },
  methods: {
    // 查询题库
    getQuestionList() {
      uni.showLoading();
      getSupervisionQuestion().then(res => {
        let data = res || [];
        this.question = JSON.parse(JSON.stringify(data));
        let subject = {};
        this.question.forEach(t => {
          if (!subject[t.projectCore]) {
            subject[t.projectCore] = {
              name: t.name,
              projectCore: t.projectCore,
              children: []
            }
          }
          subject[t.projectCore].children.push(t);
        })
        for(let key in subject) {
          this.subjectList.push(subject[key]);
        }
        console.log(this.subjectList)
        uni.hideLoading();
      })
    },
    checkAll() {
      this.subjectList.forEach(item => {
        item.children.forEach(t => {
          this.$set(t, 'value', 0);
        })
      })
    },
    checkItem(e, row) {
      let value = e.detail.value;
      this.$set(row, 'value', value);
    },
    // 选图片、
    chooseImg(row){
      if (this.imgList.length >= 20) {
        uni.showToast({
          title: '最多只能上传20张图片',
          icon:'none',
          duration: 2000
        })
        return;
      }
      uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], //从相册选择
        success:  (res)=> {
          // 上传图片
          this.uploadImg(res);
        }
      });
    },
    // 上传
    uploadImg({ tempFilePaths }) {
      let url= process.env.VUE_APP_BASE_URL + '/files/book-upload';
      let token = uni.getStorageSync('token');
      uni.showLoading();
      uni.uploadFile({
        url,
        filePath: tempFilePaths[0],
        name: 'file',  //后台接收字段名
        formData: {},
        header:{
          "Content-Type": "multipart/form-data",
          'x-token': token || '1234567890'
        },
        success: (res) => {
          uni.hideLoading()
          let result=JSON.parse(res.data||'{}')
          console.log('上传返回===', result)
          if (result.code == 200){
            // 图片url加入显示序列
            let obj = {
              filePath: tempFilePaths[0],
              fileId:result.data.fileId
            };
            this.imgList.push(obj);
          }else{
            uni.showToast({
              title: result.msg||'图片上传失败',
              icon:'none',
              duration: 2000
            })
          }
        },
        fail:(err)=>{
          uni.hideLoading()
          console.log('请求失败_______________',err)
        }
      })
    },
    deleteImg(index) {
      this.imgList.splice(index, 1);
    },
    preview(list = [], current){
      uni.previewImage({
        urls: list.map(t => t.filePath),
        current,
        fail() {
          uni.showToast('打开图片失败！')
        }
      })
    },
    submit() {
      if (!this.formData.supervisionUserName) {
        return uni.showToast({
          title: '请输入隔离点负责人',
          icon: 'none'
        })
      }
      if (!this.formData.supervisionPhone) {
        return uni.showToast({
          title: '请输入隔离点负责人联系电话',
          icon: 'none'
        })
      }
      let msg = '';
      this.question.forEach(t => {
        if (t.workText) {
          if (t.value === undefined || t.value === '') {
            return msg = '有未填写的项目';
          }
          if (t.value == 1 && !t.text) {
            return msg = '未落实项目请填写情况说明';
          }
        }
      })
      if (msg) {
        return uni.showToast({
          title: msg,
          icon: 'none'
        })
      }
      let projects = this.question.map(t => {
        let text = '';
        if (t.workText) {
          if (t.value == 0) text = '已落实';
          if (t.value == 1) text = t.text || '未落实';
        }
        if (t.projectId == '10010')text = t.text || '';
        return {
          projectId: t.projectId,
          text: text,
        }
      })
      this.formData.supervisionRelationProjects = projects;
      this.formData.fileId = this.imgList.map(t => t.fileId).join(',');
      addSupervision(this.formData).then(res => {
        uni.navigateTo({
          url: 'sucess'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {

}
.block-title {
  font-size: 40rpx;
  color: #000000;
  font-weight: 600;
  border-top: 30rpx solid #f9f9f9;
  border-bottom: 1px solid #f9f9f9;
  padding: 30rpx 40rpx;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
}
.sub-title {
  font-size: 30rpx;
  padding: 20rpx 40rpx;
  font-weight: bold;
}
.info {
  font-size: 30rpx;
  padding-left: 40rpx;
  padding-right: 40rpx;
  &-item {
    display: flex;
    justify-content: space-between;
    // padding-top: 40rpx;
    // padding-bottom: 40rpx;
    padding-top: 18rpx;
    padding-bottom: 18rpx;
    border-bottom: 1px solid #f9f9f9;
    font-weight: 500;
    &:last-child {
      border-bottom: 0;
    }
  }
  .input-right {
    text-align: right;
    width:60%;
  }
}
.check-all {
  color: #53adf3;
  font-size: 30rpx;
  display: inline-block;
}
.subject-content {
  font-size: 30rpx;
  .block-title {
    border-top: none;
  }
  .title {
    text-align: center;
    font-size: 40rpx;
    color: #000000;
    font-weight: 600;
    padding: 30rpx 40rpx;
    background-color: #f9f9f9;
  }
  .subject-item {
    background-color: #fff;
    border-bottom: 30rpx solid #f9f9f9;
  }
  .form-title {
    font-size: 32rpx;
    color: #666;
    margin-bottom: 20rpx;
  }
  .form-ext {
    margin-top: 30rpx;
    .form-title {
      margin-top: 20rpx;
    }
  }
  textarea {
    min-height: 200rpx;
    padding: 10rpx 0;
    &::-webkit-input-placeholder {
      color: #ccc;
    }
  }
  .my-raido {
    /deep/ .checklist-group {
      justify-content: space-between;
    }
    /deep/ .checklist-box {
      width: 260rpx;
    }
  }
}
.flex-box {
  padding: 20rpx 30rpx;
}
.handle-btn {
  padding: 40rpx 30rpx;
  background-color: #f9f9f9;
  button {
    background: #2c9af1;
  }
}
.unload-item{
  padding: 20rpx 30rpx;
  display: flex;
  // justify-content: space-between;
  flex-direction: row;
  flex-wrap: wrap;
  .upload-btn{
    width: 209rpx;
    height: 209rpx;
    background: rgba(227, 239, 253, 1);
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    margin: 0 30rpx 30rpx 0;
    .close{
      position: absolute;
      right: -10rpx;
      top: -25rpx;
      height: 36prx;
      width: 36rpx;
      border-radius: 50%;
      overflow: hidden;
      .close-img{
        width: 100%;
        height: 100%;
        z-index: 10;
      }
    }
    .full-img{
      width: 100%;
      height: 100%;
      border-radius: 16rpx;
    }
    .middle-img{
      width: 48rpx;
      height: 48rpx;
    }
    &:nth-child(3n){
      margin:0 0 30rpx 0;
    }
  }
}
</style>